﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AgileShare.Framework.Entities
{
	/// <summary>
	/// Extension methods to convert SPListItems with wrapper Entities
	/// </summary>
	public static class SPEntitiesExtensions
	{
		/// <summary>
		/// Casts the SPListItems in the collection to entities.
		/// </summary>
		/// <typeparam name="T">The Entity Type. Needs to inherit from SPEntityBase.</typeparam>
		/// <param name="items">The items.</param>
		/// <returns>A List of entities.</returns>
		public static List<T> ToEntities<T>(this SPListItemCollection items) where T : SPEntityBase
		{
			var entities = SPEntitiesExtensions.ToEntities<T>(items.Cast<SPListItem>());
			return entities;			
		}

		/// <summary>
		/// Casts the SPListItems in the collection to entities.
		/// </summary>
		/// <typeparam name="T">The Entity Type. Needs to inherit from SPEntityBase.</typeparam>
		/// <param name="items">The items.</param>
		/// <returns>A List of entities.</returns>
		public static List<T> ToEntities<T>(this IEnumerable<SPListItem> items) where T : SPEntityBase
		{
			var entities = new List<T>();
			if (items != null)
			{
				entities = items.Select(x => (T)Activator.CreateInstance(typeof(T), x)).Where(x => x.IsValidEntity == null || x.IsValidEntity == true).ToList();
			}
			return entities;
		}
	}
}
